package com.chinaunicom.club.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import com.chinaunicom.club.dao.ActivityMapper;
import com.chinaunicom.club.model.Activity;
import com.chinaunicom.club.service.IActivity;

@Service
public class ActivityImpl implements IActivity {

	@Resource
	private ActivityMapper dao;
	
	@Override
	public int deleteByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return dao.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(Activity record) {
		// TODO Auto-generated method stub
		return dao.insert(record);
	}

	@Override
	public int insertSelective(Activity record) {
		// TODO Auto-generated method stub
		return dao.insertSelective(record);
	}

	@Override
	public Activity selectByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return dao.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(Activity record) {
		// TODO Auto-generated method stub
		return dao.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByPrimaryKey(Activity record) {
		// TODO Auto-generated method stub
		return dao.updateByPrimaryKey(record);
	}

	@Override
	public List<Activity> queryAll(Activity activity) {
		// TODO Auto-generated method stub
		return dao.queryAll(activity);
	}

	@Override
	public int check(int id, int checkStatus) {
		// TODO Auto-generated method stub
		Activity activity = new Activity();
		activity.setId(id);
		if(checkStatus==1){
			activity.setCheckStatus("审核通过");
		}else if(checkStatus==0){
			activity.setCheckStatus("审核不通过");
		}
		return dao.updateByPrimaryKeySelective(activity);
	}

	@Override
	public boolean exportAllActivities(HttpServletRequest request, HttpServletResponse response) {
		//1.从数据库中取出所有的活动信息
		List<Activity> activities = dao.queryAll(null);
		//2.将所有的活动信息导出到excel表格中，获得该Excel表格的名字
		String excelName = exportExcel(activities);
		//3.提供该表格的下载
		return downloadExcel(excelName,request,response);
	}

	/**
	 * 提供某个文件的下载
	 * @param excelName
	 * @param response 
	 * @param request 
	 * @return
	 */
	private boolean downloadExcel(String excelName, HttpServletRequest request, HttpServletResponse response) {
		//将File对象指向Excel实体
		File file = new File(excelName);
		//设置响应头和客户端保存文件名
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition","attachment;fileName="+file.getName());
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			//打开本地文件流
			inputStream = new FileInputStream(file);
			//激活下载操作
			outputStream = response.getOutputStream();
			//循环写入输出流
			byte[] b = new byte[1024];
			int len = -1;
			while((len=inputStream.read(b))!=-1){
				outputStream.write(b, 0, len);
				outputStream.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if(outputStream!=null){
					outputStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
			try {
				if(inputStream!=null){
					inputStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/**
	 * 该方法可以将数据库的数据导出到Excel表格上
	 * @param activities
	 * @return 导出的Excel表格的名字
	 */
	private String exportExcel(List<Activity> activities) {
		//1.获取HSSFWorkbook对象
		HSSFWorkbook workbook = new HSSFWorkbook();
		//2.获取Sheet对象
		HSSFSheet sheet = workbook.createSheet("活动信息");
		//3.创建样式
		HSSFCellStyle style = workbook.createCellStyle();
		//4.设置对齐方式
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);
		//5.创建字体
		//HSSFFont font = workbook.createFont();
		//font.setBoldweight((short)24);
		//font.setFontHeightInPoints((short)30);
		//6.将字体添加到样式中
		//style.setFont(font);
		//7.创建第一行
		HSSFRow row0 = sheet.createRow(0);
		//8.第一行15列合并单元格（有效的数据字段只有15列）
		CellRangeAddress range = new CellRangeAddress(0,0,0,14);
		sheet.addMergedRegion(range);
		//9.创建第一行的第一个单元格，写入标题
		HSSFCell row0Cell0 = row0.createCell(0);
		row0Cell0.setCellValue("活动信息详情列表");
		//10.显式给第一行的第一个单元格添加样式
		row0Cell0.setCellStyle(style);
		//11.创建第二行，写入字段
		HSSFRow row1 = sheet.createRow(1);
		//构造活动表有效数据字段的数组
		String[] metas = {"organizers","activity_date","location","content","estimated_number","estimated_advertising_fee",
				"estimated_material_fee","estimated_workplace_fee","estimated_others_fee","actual_number",
				"actual_advertising_fee","actual_material_fee","actual_workplace_fee","actual_others_fee","check_status"};
		//开始进行字段数据的填充
		for(int i=0; i<metas.length; i++){
			//每次循环创建一个单元格
			HSSFCell row1Cell = row1.createCell(i);
			//给该单元格设置值
			row1Cell.setCellValue(metas[i]);
			//给该单元格添加样式
			row1Cell.setCellStyle(style);
		}
		//12.写入具体的业务数据
		//计算出当前数据有多少行，则实际需要的行数=标题行+字段行+数据行
		int dataRowNum = activities.size();		
		for(int i=0;i<dataRowNum;i++){
			//每循环一次，创建新的一行
			HSSFRow row = sheet.createRow(i+2);
			//创建单元格，将每行数据的内容填充到工作表中，并设置样式
			//组织者
			HSSFCell row1Cell0 = row.createCell(0);
			row1Cell0.setCellValue(activities.get(i).getOrganizers());
			row1Cell0.setCellStyle(style);
			//活动时间
			HSSFCell row1Cell1 = row.createCell(1);
			row1Cell1.setCellValue(activities.get(i).getActivityDate());
			row1Cell1.setCellStyle(style);
			//地点
			HSSFCell row1Cell2 = row.createCell(2);
			row1Cell2.setCellValue(activities.get(i).getLocation());
			row1Cell2.setCellStyle(style);
			//内容
			HSSFCell row1Cell3 = row.createCell(3);
			row1Cell3.setCellValue(activities.get(i).getContent());
			row1Cell3.setCellStyle(style);
			//预计人数
			HSSFCell row1Cell4 = row.createCell(4);
			row1Cell4.setCellValue(activities.get(i).getEstimatedNumber());
			row1Cell4.setCellStyle(style);
			//预计广告费用
			HSSFCell row1Cell5 = row.createCell(5);
			row1Cell5.setCellValue(activities.get(i).getEstimatedAdvertisingFee().doubleValue());
			row1Cell5.setCellStyle(style);
			//预计材料费用
			HSSFCell row1Cell6 = row.createCell(6);
			row1Cell6.setCellValue(activities.get(i).getEstimatedMaterialFee().doubleValue());
			row1Cell6.setCellStyle(style);
			//预计场地费用
			HSSFCell row1Cell7 = row.createCell(7);
			row1Cell7.setCellValue(activities.get(i).getEstimatedWorkplaceFee().doubleValue());
			row1Cell7.setCellStyle(style);
			//预计其它费用
			HSSFCell row1Cell8 = row.createCell(8);
			row1Cell8.setCellValue(activities.get(i).getEstimatedOthersFee().doubleValue());
			row1Cell8.setCellStyle(style);
			//实际人数
			HSSFCell row1Cell9 = row.createCell(9);
			row1Cell9.setCellValue(activities.get(i).getActualNumber().doubleValue());
			row1Cell9.setCellStyle(style);
			//实际广告费用
			HSSFCell row1Cell10 = row.createCell(10);
			row1Cell10.setCellValue(activities.get(i).getActualAdvertisingFee().doubleValue());
			row1Cell10.setCellStyle(style);
			//实际材料费用
			HSSFCell row1Cell11 = row.createCell(11);
			row1Cell11.setCellValue(activities.get(i).getActualMaterialFee().doubleValue());
			row1Cell11.setCellStyle(style);
			//实际场地费用
			HSSFCell row1Cell12 = row.createCell(12);
			row1Cell12.setCellValue(activities.get(i).getActualWorkplaceFee().doubleValue());
			row1Cell12.setCellStyle(style);
			//实际其它费用
			HSSFCell row1Cell13 = row.createCell(13);
			row1Cell13.setCellValue(activities.get(i).getActualOthersFee().doubleValue());
			row1Cell13.setCellStyle(style);
			//审核状态
			HSSFCell row1Cell14 = row.createCell(14);
			row1Cell14.setCellValue(activities.get(i).getCheckStatus());
			row1Cell14.setCellStyle(style);
		}
		//13.生成具体的Excel文件
		OutputStream output = null;
		File file = new File("c:\\activity.xls");
		try {
			output = new FileOutputStream(file);
			workbook.write(output);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return file.getPath();
	}

	@Override
	public boolean exportActivityById(int id, HttpServletRequest request, HttpServletResponse response) {
		//从数据库中取出单个活动的信息
		Activity activity = dao.selectByPrimaryKey(id);
		List<Activity> list = new ArrayList<>();
		list.add(activity);
		//将数据写入到Excel表格
		String excelName = exportExcel(list);
		//提供表格的下载
		return downloadExcel(excelName, request, response);
	}

	@Override
	public List<Activity> pageQueryAll(int page,int rows) {
		// TODO Auto-generated method stub
		int start = (page-1)*rows;
		int end = page*rows;
		return dao.pageQueryAll(start,end);
	}

	@Override
	public int count(Integer id) {
		// TODO Auto-generated method stub
		return dao.count(id);
	}

}
